package com.example.administrator.yunniuusedcar.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Administrator on 2017/12/2.
 */

public class LetterBar extends View {

    /** 索引字母颜色 */
    private static final int LETTER_COLOR = 0xff595959;

    /** 26个字母 */
    public static final String[] LETTERS = {
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
            "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
    };

    /** 单元格高度 */
    private float mCellHeight;

    private Paint mPaint;
    private TextView tvLetter;

    public LetterBar(Context context) {
        super(context);
        init();
    }

    public LetterBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(LETTER_COLOR);
        mPaint.setTextSize(dp2px(16));  // 16sp
        mPaint.setAntiAlias(true);      // 去锯齿，让字体边缘变得平滑
    }

    private int dp2px(int dp) {
        return (int) (getResources().getDisplayMetrics().density * dp + 0.5f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 绘制26个字母
        for (int i = 0; i < LETTERS.length; i++) {
            // 要绘制的字母
            String letter = LETTERS[i];

            // x = 单元格宽度/2 - 字母宽度/2；
            // y = 单元格高度/2 + 字母高度/2  + 单元格高度 * k(K的取值为0,1,2...)
            float x = getWidth() / 2 -  getTextWidth(letter) / 2;
            float y = mCellHeight / 2 + getTextHeight(letter) / 2
                    + mCellHeight * i ;

            canvas.drawText(letter, x, y, mPaint);
        }
    }

    /** 获取字母的宽 */
    public int getTextWidth(String text) {
        Rect rect = new Rect();
        mPaint.getTextBounds(text, 0, text.length(), rect);
        return rect.width();
    }

    /** 获取字母的高 */
    public int getTextHeight(String text) {
        Rect rect = new Rect();
        mPaint.getTextBounds(text, 0, text.length(), rect);
        return rect.height();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // 单元格的高度
        mCellHeight = getMeasuredHeight() / LETTERS.length;
    }

    private int index;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                // 计算按下的是哪一个字母
                index = (int) (event.getY() / mCellHeight);
                if (index >= 0 && index < LETTERS.length) {
                    String letter = LETTERS[index];
                    // System.out.println("---------按下的字母：" + letter);

                    // 3. 当事件发生时，回调监听器对应的方法
                    if (mOnLetterSelectedListener != null)
                        mOnLetterSelectedListener.onLetterSelected(letter, index);

                    // 显示选中的字母
                    tvLetter.setVisibility(View.VISIBLE);
                    tvLetter.setText(letter);
                }

                break;
            case MotionEvent.ACTION_MOVE:

                // 计算按下的是哪一个字母
                int tempIndex = (int) (event.getY() / mCellHeight);
                if (tempIndex >= 0 && tempIndex < LETTERS.length) {

                    // 当用户新选中的字母与当前字母不一样时，才打印
                    if (tempIndex != index) {
                        index = tempIndex;
                        String letter = LETTERS[index];
                        // System.out.println("---------按下的字母：" + letter);

                        // 3. 当事件发生时，回调监听器对应的方法
                        if (mOnLetterSelectedListener != null)
                            mOnLetterSelectedListener.onLetterSelected(letter, index);

                        // 显示选中的字母
                        tvLetter.setVisibility(View.VISIBLE);
                        tvLetter.setText(letter);
                    }
                }

                break;
            case MotionEvent.ACTION_UP:
                // 隐藏选中的字母
                tvLetter.setVisibility(View.GONE);
                break;
        }
        return true;
    }

    public void setTextView(TextView tvLetter) {
        this.tvLetter = tvLetter;
    }

    // 1. 定义一个接口（监听器）
    public interface OnLetterSelectedListener {
        /**
         * 选中的字母发生改变了
         *
         * @param letter 用户新选中的字母
         * @param index 选中的是哪一个字母
         */
        void onLetterSelected(String letter, int index);
    }

    // 2. 定义一个监听器变量，并提供set方法
    public OnLetterSelectedListener mOnLetterSelectedListener;

    public void setOnLetterSelectedListener(OnLetterSelectedListener listener) {
        this.mOnLetterSelectedListener = listener;
    }
}
